<script>
import axios from 'axios';
export default {
    name: "itemUpload",
    props: {
        value: [Number, String, Array, Object, undefined, null],
        config: Object,
        change: Function,
    },
    data() {
        return {
            configSelf: {},
            options: null,
            fileList: []
        };
    },
    watch: {
        config: {
            handler(val) {
                if (val.fileApi) {
                    this.configSelf = { ...this.config };
                }
            },
            deep: true,
            immediate: true
        },
        fileList: {
            handler(val) {
                console.log(val)
                this.change(val);
            },
            deep: true
        },
        value: {
            handler(val) {
                if(val) this.fileList = val;
            },
            deep: true,
            immediate: true,
        }
    },
    methods: {
        setValueSelf(value) {
            this.change(value);
        },
        onRemove(e) {
            const index = this.fileList.findIndex(a => a.name === e.name);
            if (index >= 0) this.fileList.splice(index, 1);
        },
        async uploadFile(e) {
            try {
                let FormDatas = new FormData();
                FormDatas.append("file", e.file);
                console.log(this.configSelf.fileApi)
                const res = await axios.post(this.configSelf.fileApi, FormDatas, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                this.fileList.push({ name: e.file.name, url: res.data.url });
            } catch (error) {
                console.log(error);
            }
        },
    },
    render() {
        return (
            <el-upload
                class="upload-demo"
                props={{ ...this.configSelf, onRemove: this.onRemove }}
                action=""
                http-request={this.uploadFile}
                file-list={this.fileList}>
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">{this.configSelf.tip}</div>
            </el-upload>
        );
    },
};
</script>
